package handlers

import (
	"github.com/gin-gonic/gin"
	"news-core/models"
	"news-core/pkg"
	"strconv"
)

func Res(c *gin.Context) {
	uid := c.Query("uid")
	token, _ := pkg.TokenHandler(uid)
	tel := c.PostForm("tel")
	password := c.PostForm("password")

	if !pkg.RegTel(tel) {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "手机号码格式错误",
		})
		return
	}
	if !pkg.RegPassword(password) {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "密码不少于6位数",
		})
		return
	}

	user := models.User{
		Tel:      tel,
		Password: pkg.Md5Str(password),
	}

	err := models.DB.Create(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "注册失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "注册成功",
		"data": token,
	})
	return

}

func Login(c *gin.Context) {
	uid := c.PostForm("uid")
	tel := c.PostForm("tel")
	password := c.PostForm("password")
	var user models.User
	if pkg.Md5Str(password) != user.Password {
		c.JSON(200, gin.H{
			"code": 500,
			"mag":  "密码不正确",
		})
		return
	}
	err := models.DB.Where("tel=?", tel).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不存在",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": gin.H{
			"uid": uid,
		},
	})
	return

}

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	userId, _ := strconv.Atoi(c.PostForm("user_id"))
	news := models.New{
		Title:        title,
		Content:      content,
		Img:          img,
		LikeCount:    0,
		CommentCount: 0,
		UserId:       userId,
	}

	err := models.DB.Create(news).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func Upload(c *gin.Context) {
	file, err := c.FormFile("img")
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "图片获取失败",
		})
		return
	}

	path := "static/img/" + file.Filename
	err = c.SaveUploadedFile(file, path)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "上传失败",
		})
		return
	} else {
		url := "http://" + c.Request.Host + "/" + path
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "上传成功",
			"data": url,
		})
		return
	}
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var count int64
	models.DB.Model(&models.New{}).Count(&count)
	var news []models.New
	err := models.DB.Preload("User").Offset(offset).Limit(size).Find(news).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": news,
	})
	return

}
